package net.ojbk.util;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import net.ojbk.po.Email;

/**
 * 发送 一封自定义邮件
 * 
 * @author twobox
 *
 */
public class EmailTool {
	private static final String from = "ojbk@ojbk.net";
	private static final String emailPassword = "Twobox2005";
	
	public static boolean sendEmail(Email email) {
		boolean flag = false;
		// 收件人电子邮箱
		String to = email.getToEmail();
	    String title = email.getTitle();
	    String content = email.getContent();
	    
	    // 指定发送邮件的主机为 smtp.mxhichina.com
	    String host = "42.120.226.4";  // 邮件服务器
	 
	    // 获取系统属性
	    Properties properties = System.getProperties();
	 
	    // 设置邮件服务器
	    properties.setProperty("mail.smtp.host", host);
	    properties.put("mail.smtp.localhost", "127.0.0.1");
	    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
	    properties.put("mail.smtp.socketFactory.port", "465");
	    properties.put("mail.smtp.auth", "true");
	   
	    // 获取默认session对象
	    Session session = Session.getInstance(properties,new Authenticator(){
	      public PasswordAuthentication getPasswordAuthentication()
	      {
	       return new PasswordAuthentication(from, emailPassword); //发件人邮件用户名、密码
	      }
	     });
	 
	      try{
	         // 创建默认的 MimeMessage 对象
	         MimeMessage message = new MimeMessage(session);
	         
	         
	         
	         // Set From: 头部头字段
	         message.setFrom(new InternetAddress(from));
	 
	         // Set To: 头部头字段
	         message.addRecipient(Message.RecipientType.TO,
	                                  new InternetAddress(to));
	 
	         // Set Subject: 头部头字段
	         message.setSubject(title);
	 
	         // 设置消息体
	         message.setText(content);
	 
	         // 发送消息
	         Transport.send(message);
	         System.out.println("Sent message successfully....from "
	         		+ from
	         		+ ", to "
	         		+ to
	         		+ "");
	         flag = true;
	      }catch (MessagingException mex) {
	         mex.printStackTrace();
	      }
	      
		return flag;
	}
	
	public static void main(String[] args) {
		Email email = new Email();
		
		email.setToEmail("200562421@qq.com");
		email.setTitle("这是第一封邮件。") ;
		email.setContent("这是邮件信息体，你收到了第一封邮件。");
		
		for (int i=0; i<5; i++) {
			EmailTool.sendEmail(email);
		}
		
	}
}
